package com.wangbo.box.singleton;

import java.util.concurrent.ArrayBlockingQueue;
import java.util.concurrent.ThreadPoolExecutor;
import java.util.concurrent.TimeUnit;

/**
 * 懒汉式 双检锁，lazy load思想，用到时在创建，不用时不创建。
 */
public class LazySingleton {

    private static volatile LazySingleton instance; //volatile 禁止new LazySingleton()非原子操作 指令重排

    private LazySingleton() {
        System.out.println(Thread.currentThread().getName() + "初始化");
    }

    public static LazySingleton getInstance() {
        if (instance == null) {
            synchronized (LazySingleton.class) {
                if (instance == null) {
                    instance = new LazySingleton();
                }
            }
        }
        return instance;
    }

    public static void main(String[] args) {
        ThreadPoolExecutor executor = new ThreadPoolExecutor(10, 10, 0L, TimeUnit.MILLISECONDS, new ArrayBlockingQueue<>(10));
        for (int i = 10; i >= 1; i--) {
            executor.execute(new Thread(() -> {
                System.out.println(Thread.currentThread().getName() + "获取instance");
                LazySingleton.getInstance();
            }, "线程" + i));
        }
        executor.shutdown();
    }

}
